package com.ranga.mselfcare;

import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Messenger;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;

import com.ranga.mselfcare.config.Config;
import com.ranga.mselfcare.entity.TopUp;
import com.ranga.mselfcare.services.TopUpSelfService;

@SuppressLint("HandlerLeak")
public class TopUpSelfActivity extends Activity implements OnClickListener{

	private ProgressDialog progressDialog;
	private int status = Config.PROGRESS_STOPPED;
	private final String TAG = "TopUpActivity";
	private String token = "";
	private String phoneNumber = "";
	private String amount;
	
	private Spinner spinTopUpAmount;
	private Button btnTopUp;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		progressDialog = new ProgressDialog(this);
		setContentView(R.layout.activity_topup_self);
		
		spinTopUpAmount = (Spinner) findViewById(R.id.spinTopUpAmount);
		btnTopUp = (Button) findViewById(R.id.bTopUp);
		
		initializeDataFromSharedPreference();
		
		btnTopUp.setOnClickListener(this);
		spinTopUpAmount.setAdapter(createSpinnerAdapter());
		
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		hideProgressDialog();
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (status == Config.PROGRESS_STARTED) {
			progressDialog.setMessage(this.getString(R.string.getting_balance));
			progressDialog.show();
		}
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		outState.putInt(Config.STATUS, status);
		super.onSaveInstanceState(outState);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		status = savedInstanceState.getInt(Config.STATUS);
	}
	
	private boolean isNetworkAvailable() {
		ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

		boolean networkAvailable = false;

		if (networkInfo != null && networkInfo.isConnectedOrConnecting()) {
			networkAvailable = true;
		} else {
			AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
			alertDialog.setTitle(getString(R.string.alert));
			alertDialog
					.setMessage(getString(R.string.no_internet_connectivity));
			alertDialog.setPositiveButton(getString(R.string.okay),
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							startActivity(new Intent(
									WifiManager.ACTION_PICK_WIFI_NETWORK));
						}
					});
			alertDialog.show();
		}
		return networkAvailable;
	}
	
	private Handler progressHandler = new Handler() {
		public void handleMessage(Message message) {

			status = message.arg1;

			switch (status) {

			case Config.PROGRESS_STARTED:
				Log.i(TAG, "Progress Started");
				progressDialog.setMessage(TopUpSelfActivity.this
						.getString(R.string.toppingup));
				progressDialog.show();
				break;
			case Config.PROGRESS_STOPPED:
				Log.i(TAG, "Progress stopped");
				hideProgressDialog();
				status = Config.PROGRESS_STOPPED;
				Toast.makeText(TopUpSelfActivity.this, "Error Topping up!",
						Toast.LENGTH_SHORT).show();
				break;
			case Config.PROGRESS_SUCCESS:
				Log.i(TAG, "Progress success");
				status = Config.PROGRESS_STOPPED;
				hideProgressDialog();
				break;
			}
		};
	};

	private Handler serviceResultHandler = new Handler() {
		public void handleMessage(Message message) {
			Bundle resultBundle = message.getData();
			int errorCode = 0;
			
			if (resultBundle.containsKey(Config.RESPONSE_ERROR)) {
				errorCode = Integer.parseInt(resultBundle.getString(Config.RESPONSE_ERROR));
			}
			
			if (errorCode == 200) {
				AlertDialog.Builder alertDialog = new AlertDialog.Builder(
						TopUpSelfActivity.this);
				alertDialog.setTitle(getString(R.string.alert));
				alertDialog.setMessage("You have successfully recharged your account by " + amount);
				alertDialog.setPositiveButton(getString(R.string.okay),
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog, int which) {
								Intent intent = new Intent(TopUpSelfActivity.this, MainMenuActivity.class);
								finish();
								startActivity(intent);
							}
						});
				alertDialog.show();
			} else if (errorCode == 405) {
				displayErrorMessage(R.string.alert_token_expired);
				startTokenInitializeActivity();
			} else {
				displayErrorMessage(R.string.alert_top_up_failed);
				status = Config.PROGRESS_STOPPED;
			}
		};
	};
	
	private void hideProgressDialog() {
		if (progressDialog.isShowing()) {
			progressDialog.dismiss();
		}
	}
	
	private void initializeDataFromSharedPreference() {
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(this);
		token = prefs.getString(Config.TOKEN, "");
		phoneNumber = prefs.getString(Config.PHONE_NUMBER, "");

		if (token.contentEquals("")) {
			Log.e(TAG, "token not saved from previous activity");
			AlertDialog.Builder alertTokenNotRecieved = new AlertDialog.Builder(
					this);
			alertTokenNotRecieved.setTitle(this.getString(R.string.alert));
			alertTokenNotRecieved
					.setMessage(getString(R.string.alert_token_not_saved));
			alertTokenNotRecieved.setPositiveButton(getString(R.string.okay),
					new DialogInterface.OnClickListener() {

			
				@Override
						public void onClick(DialogInterface dialog, int which) {
							startTokenInitializeActivity();
						}
					});
		}
	}
	
	
	private void startTokenInitializeActivity() {
		Intent tokenInitialize = new Intent(TopUpSelfActivity.this, TokenInitializeActivity.class);
		finish();
		startActivity(tokenInitialize);
	}
	
	private ArrayAdapter<String> createSpinnerAdapter() {
		ArrayList<String> spinnerItems = new ArrayList<String>();
		spinnerItems.add("20");
		spinnerItems.add("50");
		spinnerItems.add("100");
		spinnerItems.add("200");
		spinnerItems.add("500");
		spinnerItems.add("1000");
		
		return new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, spinnerItems);
	}

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.bTopUp:
			if (isNetworkAvailable()) {
				TopUp topUp = new TopUp();
				amount = spinTopUpAmount.getSelectedItem().toString();
				topUp.setAmount(Double.parseDouble(amount));
				topUp.setMethod(1);
				topUp.setMsisdn(phoneNumber);
				topUp.setToken(token);
				if (status == Config.PROGRESS_STOPPED) {
					Intent topUpIntent = new Intent(TopUpSelfActivity.this, TopUpSelfService.class);
					Messenger resultMessenger = new Messenger(
							serviceResultHandler);
					Messenger progressMessenger = new Messenger(
							progressHandler);
					Bundle bundle = new Bundle();
					bundle.putString(Config.PHONE_NUMBER, phoneNumber);
					bundle.putString(Config.TOKEN, token);
					bundle.putParcelable(Config.TOPUP, topUp);
					try {
						Log.w(TAG, "inside try");
						topUpIntent.putExtras(bundle);
						topUpIntent.putExtra(Config.RESULT_MESSENGER,
								resultMessenger);
						topUpIntent.putExtra(Config.PROGRESS_MESSENGER,
								progressMessenger);
						startService(topUpIntent);
					} catch (SecurityException e) {
						Log.w(TAG, "Unable to start get login service: "
								+ e.toString());
					}
				}
			}
			break;
		}
		
	}
	
	private void displayErrorMessage(int message) {
		AlertDialog.Builder alertDialog = new AlertDialog.Builder(
				TopUpSelfActivity.this);
		alertDialog.setTitle(getString(R.string.alert));
		alertDialog.setMessage(getString(message));
		alertDialog.setPositiveButton(getString(R.string.okay),
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
		alertDialog.show();
	}
}
